package main

import (
	"context"
	"fmt"
	"gateway/global/model"
	"gateway/global/pkg"
	user "gateway/kitex_gen/user"
	"math/rand"
	"time"
)

// UserServiceImpl implements the last service interface defined in the IDL.
type UserServiceImpl struct{}

// User implements the UserServiceImpl interface.
func (s *UserServiceImpl) User(ctx context.Context, req *user.UserReq) (resp *user.UserResp, err error) {
	// TODO: Your code here...
	return
}

// UserCodeLogin implements the UserServiceImpl interface.
func (s *UserServiceImpl) UserCodeLogin(ctx context.Context, req *user.UserCodeLoginReq) (resp *user.UserLoginResp, err error) {
	// TODO: Your code here...
	code, _ := model.RDB.Get(model.Ctx, fmt.Sprintf("%s:code", req.Phone)).Result()
	if code != req.Code || code == "" {
		return nil, fmt.Errorf("验证码错误")
	}
	var users model.User
	model.DB.Where("phone = ?", req.Phone).Find(&users)
	if users.ID == 0 {
		users = model.User{
			Phone:    req.Phone,
			OpenId:   0,
			Role:     "乘客",
			NickName: fmt.Sprintf("乘客%s", req.Phone),
			Status:   "正常",
		}
		model.DB.Create(&users)
		return &user.UserLoginResp{
			NickName: users.NickName,
			UserId:   int64(users.ID),
		}, nil
	}
	return &user.UserLoginResp{
		NickName: users.NickName,
		UserId:   int64(users.ID),
	}, nil
}

// UserPasswordLogin implements the UserServiceImpl interface.
func (s *UserServiceImpl) UserPasswordLogin(ctx context.Context, req *user.UserPasswordLoginReq) (resp *user.UserLoginResp, err error) {
	// TODO: Your code here...
	var User model.User
	if err := model.DB.Where("password = ? and phone = ?", pkg.Bcrype(req.Password), req.Phone).Find(&User).Error; err != nil {
		return nil, err
	}
	if User.ID == 0 {
		return nil, fmt.Errorf("账号或密码错误")
	}
	return &user.UserLoginResp{
		NickName: User.NickName,
		UserId:   int64(User.ID),
	}, nil
}

// UserWeChatLogin implements the UserServiceImpl interface.
func (s *UserServiceImpl) UserWeChatLogin(ctx context.Context, req *user.UserWeChatLoginReq) (resp *user.UserLoginResp, err error) {
	// TODO: Your code here...
	key := fmt.Sprintf("%d:wechatlogin", req.OpenId)
	count, _ := model.RDB.Get(model.Ctx, key).Int()
	if count >= 3 {
		return &user.UserLoginResp{}, fmt.Errorf("请求过于频繁，请 10 分钟后再试")
	}
	if count == 2 {
		model.RDB.Expire(model.Ctx, key, 10*time.Minute)
	}
	model.RDB.Incr(model.Ctx, key)
	
	return
}

// SeedCodeLogin implements the UserServiceImpl interface.
func (s *UserServiceImpl) SeedCodeLogin(ctx context.Context, req *user.SeedCodeReq) (resp *user.SeedCodeResp, err error) {
	// TODO: Your code here...
	code := fmt.Sprintf("%d", rand.Intn(90000)+10000)
	key := fmt.Sprintf("%s:code", req.Phone)
	model.RDB.Set(model.Ctx, key, code, 5*time.Minute)
	errs := pkg.SmsCode(req.Phone, code)
	if errs != nil {
		return nil, errs
	}
	return
}
